/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.safetytask.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.safetytask.domain.CustomForm;
import com.koron.safetytask.mapper.CustomFormDataMapper;
import com.koron.safetytask.mapper.CustomFormMapper;
import com.koron.safetytask.service.api.CustomFormService;
import com.koron.safetytask.utils.BusinessCode;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CustomFormServiceImpl implements CustomFormService {

    private final static  Logger logger = LoggerFactory.getLogger(CustomFormServiceImpl.class);


    /**
     * 批量新增
     *
     * @param customFormList
     * @param name
     * @param state
     * @return
     */
    @Override
    public MessageBean<Integer> batchInsert(List<CustomForm> customFormList, String name, Integer state, StaffBean user) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            Integer nameCount = factory.getMapper(CustomFormMapper.class).queryByName(name);
            if (nameCount > 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("表名已存在");
                return msg;
            }
            Date addTime = new Date();
            String code = UUID.randomUUID().toString().replace("-", "");
            Integer count = factory.getMapper(CustomFormMapper.class).queryByCode(code);
            // 自定义表单编码不能重复
            while (count != 0) {
                code = UUID.randomUUID().toString().replace("-", "");
                count = factory.getMapper(CustomFormMapper.class).queryByCode(code);
            }
            if (null != customFormList && customFormList.size() > 0) {
                for (CustomForm customForm : customFormList) {
                    if (StringUtils.isEmpty(customForm.getKeyName())) {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("自定义表单字段名称不能为空");
                        return msg;
                    }
                    if (StringUtils.isEmpty(customForm.getKeyType())) {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("自定义表单字段类型不能为空");
                        return msg;
                    }
                    customForm.setAddTime(addTime);
                    customForm.setAddUser(user.getCode());
                    customForm.setAddUserName(user.getName());
                    customForm.setUpdateUser(user.getCode());
                    customForm.setUpdateUserName(user.getName());
                    customForm.setUpdateTime(addTime);
                    customForm.setCode(code);
                    customForm.setName(name);
                    customForm.setState(state);
                    if (StringUtils.isEmpty(customForm.getId())) {
                        customForm.setId(DefaultIdGenerator.getInstance().generateLongId());
                    }
                }
                //批量添加自定义表单数据
                Integer integer = factory.getMapper(CustomFormMapper.class).batchInsert(customFormList);
                if (integer <= 0) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                }
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("自定义表头不能为空");
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 批量修改
     *
     * @param beanList
     * @return
     */
    @Override
    public MessageBean<Integer> batchUpdate(List<CustomForm> beanList, String name, Integer state, StaffBean user) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            List<CustomForm> addList = new ArrayList<>();
            List<CustomForm> updateList = new ArrayList<>();
            String code = null;
            Date addTime = null;
            Date updateTime = new Date();
            String addUser = null;
            String addUserName = null;
            if (null != beanList && beanList.size() > 0) {
                for (CustomForm customForm : beanList) {
                    if (StringUtils.isEmpty(customForm.getKeyName())) {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("自定义表单字段名称不能为空");
                        return msg;
                    }
                    if (StringUtils.isEmpty(customForm.getKeyType())) {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("自定义表单字段类型不能为空");
                        return msg;
                    }
                    if (StringUtils.isEmpty(customForm.getId())) {
                        addList.add(customForm);
                    } else {
                        updateList.add(customForm);
                    }
                }
                for (CustomForm customForm : updateList) {
                    code = customForm.getCode();
                    addTime = customForm.getAddTime();
                    addUser = customForm.getAddUser();
                    addUserName = customForm.getAddUserName();
                    customForm.setName(name);
                    customForm.setState(state);
                    customForm.setUpdateTime(updateTime);
                    customForm.setUpdateUser(user.getCode());
                    customForm.setUpdateUserName(user.getName());
                }
                for (CustomForm customForm : addList) {
                    customForm.setId(DefaultIdGenerator.getInstance().generateLongId());
                    customForm.setAddTime(addTime);
                    customForm.setAddUser(addUser);
                    customForm.setAddUserName(addUserName);
                    customForm.setUpdateTime(updateTime);
                    customForm.setUpdateUser(user.getCode());
                    customForm.setUpdateUserName(user.getName());
                    customForm.setCode(code);
                    customForm.setName(name);
                    customForm.setState(state);
                    if (StringUtils.isEmpty(customForm.getId())) {
                        customForm.setId(DefaultIdGenerator.getInstance().generateLongId());
                    }
                }
                if (null != addList && addList.size() > 0) {
                    factory.getMapper(CustomFormMapper.class).batchInsert(addList);
                }
                Integer integer = factory.getMapper(CustomFormMapper.class).batchUpdate(updateList);
                if (integer <= 0) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    @Override
    public MessageBean<Integer> batchDelete(List<String> idList) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try (SessionFactory factory = new SessionFactory();) {
            if (null != idList && idList.size() > 0) {
                Integer integer = factory.getMapper(CustomFormMapper.class).batchDelete(idList);
                if (integer <= 0) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 列表查询所有的自定义表单
     *
     * @param start
     * @param rows
     * @return
     */
    @Override
    public MessageBean<DataBean<CustomForm>> list(String name, String addUserName, Integer start, Integer rows) {
        MessageBean<DataBean<CustomForm>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            // 获取所有表单
            List<CustomForm> list = factory.getMapper(CustomFormMapper.class).queryAll(name, addUserName);
            Integer end = (start == 0 ? rows : start + rows);
            if (end > list.size()) {
                end = list.size();
            }
            Integer totalNumber = list.size();
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<CustomForm> dataBean = new DataBean<>();
            dataBean.setList(list.subList(start, end));
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询自定义表单成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 所有确定的，可供使用的表单
     *
     * @param start
     * @param rows
     * @return
     */
    @Override
    public MessageBean<DataBean<CustomForm>> availableFormsList(Integer start, Integer rows) {
        MessageBean<DataBean<CustomForm>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            // 获取所有可用表单
            Integer end = null;
            List<CustomForm> list = factory.getMapper(CustomFormMapper.class).queryAvailableForms();
            if (rows == 0) {
                end = list.size();
            } else {
                end = (start == 0 ? rows : start + rows);
            }
            if (end > list.size()) {
                end = list.size();
            }
            Integer totalNumber = list.size();
            Integer totalPage=1;
            if (rows != 0) {
                totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            }
            DataBean<CustomForm> dataBean = new DataBean<>();
            dataBean.setList(list.subList(start, end));
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询自定义表单成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }

    }

    @Override
    public MessageBean<Integer> delete(String code) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            Integer integer = factory.getMapper(CustomFormMapper.class).queryByCode(code);
            if (integer < 1) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("不存在此表单");
                return msg;
            }
            // 查询表单是否被使用
            Integer count = factory.getMapper(CustomFormDataMapper.class).queryByTbaleCode(code);
            if (count>0){
                msg.setCode(-1);
                msg.setDescription("该表单已经引用，不能删除");
                return msg;
            }
            Integer delete = factory.getMapper(CustomFormMapper.class).delete(code);
            if (delete > 0) {
                factory.close();
                return msg;
            } else {
                factory.close();
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("自定义表单删除失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<CustomForm> queryByCode(String code, String addUser, String addUserName) {
        MessageBean<CustomForm> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<CustomForm> list = factory.getMapper(CustomFormMapper.class).queryByCondition(code, addUser, addUserName);
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setKeyCode("key" + i);
            }
            String name = list.get(0).getName();
            String code1 = list.get(0).getCode();
            CustomForm customForm = new CustomForm();
            customForm.setName(name);
            customForm.setCode(code1);
            customForm.setCustomFormList(list);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询自定义表单成功");
            msg.setData(customForm);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

}
